// import { Module } from 'vuex'
// interface UserState {
//   userInfo: any
// }
// console.log('缓存的个人信息', uni.getStorageSync('userInfo'))
// const userModule: Module<UserState, any> = {
//   namespaced: true,
//   state: () => ({
//     userInfo: uni.getStorageSync('userInfo') || null
//   }),
//   mutations: {
//     setUserInfo(state, payload) {
//       state.userInfo = payload
//     }
//   },
//   actions: {}
// }

// export default userModule
import { Module } from 'vuex'
import { clientUserInfo } from '@/utils/api/user'
// 封装本地存储操作
const STORAGE_KEY = 'userInfo'

function getLocalUserInfo(): any {
  try {
    const data = uni.getStorageSync(STORAGE_KEY)
    console.log('getLocalUserInfo', typeof data)
    let dataObj = null
    if (data) {
      dataObj = JSON.parse(data)
    }
    console.log('getLocalUserInfo', dataObj)
    return dataObj
  } catch (error) {
    console.warn('读取本地用户信息失败', error)
    return null
  }
}

function saveLocalUserInfo(userInfo: any): void {
  try {
    if (userInfo) {
      uni.setStorageSync(STORAGE_KEY, JSON.stringify(userInfo))
    } else {
      uni.removeStorageSync(STORAGE_KEY)
    }
  } catch (error) {
    console.warn('保存用户信息到本地失败', error)
  }
}

const userModule: Module<{ userInfo: any }, any> = {
  namespaced: true,
  state: () => ({
    userInfo: getLocalUserInfo()
  }),
  mutations: {
    setUserInfo(state, payload: any) {
      state.userInfo = payload
      saveLocalUserInfo(payload)
    }
  },
  actions: {
    async getUserInfo(state): Promise<void> {
      const res = await clientUserInfo()
      if (res.code === 200) {
        let data = res.data || {}
        data.isVip = data.vipCode ? data.vipCode !== 'common' : false
        console.log('登录后塞的数据是', data)
        state.commit('setUserInfo', data)
      } else {
        console.warn('获取用户信息失败或数据不完整', res)
      }
    }
  },
  getters: {
    isVip(state): boolean {
      return state.userInfo?.isVip
    }
  }
}

export default userModule
